<template>
  <div class="app-container">
    <div class="search_wapper">
      <el-form ref="form" :model="form" size="small" label-width="100px">
        <el-row>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
            <el-form-item :label="`${type==='video' ? '视频' :'文章' }标题`">
              <el-input v-model="form.title" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
            <el-form-item :label="`${type==='video' ? '视频' :'文章' }ID`">
              <el-input v-model="form.ids" placeholder="请输入id，多个id请用英文逗号隔开" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
            <el-form-item label="作者">
              <el-input v-model="form.author" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
            <el-form-item label="标签">
              <el-input v-model="form.tag" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
            <el-form-item label="关键词">
              <el-input v-model="form.keyord" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
            <el-form-item label="创建人">
              <el-input v-model="form.createBy" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
            <el-form-item label="标注状态">
              <el-select v-model="form.isTagged" placeholder="标注状态">
                <el-option label="已标注" value="true" />
                <el-option label="未标注" value="false" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
            <el-form-item label="审核状态">
              <el-select v-model="form.auditStatus" placeholder="审核状态">
                <el-option label="待审" value="Pending" />
                <el-option label="审核中" value="Auditing" />
                <el-option label="通过" value="Publish" />
                <el-option label="删除" value="Deleted" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
            <el-form-item label="外部ID">
              <el-input v-model="form.referIds" placeholder="请输入外部id，多个id请用英文逗号隔开" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="form.createAt"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
            <el-form-item label="更新时间">
              <el-date-picker
                v-model="form.updateAt"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
            <el-form-item label="发布时间">
              <el-date-picker
                v-model="form.publishAt"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>

        </el-row>
        <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
          <el-form-item label="打标时间">
            <el-date-picker
              v-model="form.tagAt"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
          <el-form-item label="">
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
        </el-col>

      </el-form>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :max-height="600"
      highlight-current-row
    >
      <el-table-column
        align="center"
        type="selection"
        width="55"
        fixed
      />
      <el-table-column fixed align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{ scope.$index }}
        </template>
      </el-table-column>
      <el-table-column fixed label="ID" align="center" width="100">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column fixed label="标题" align="center" width="260">
        <p slot-scope="scope" style="text-align: left;">
          {{ scope.row.title }}
        </p>
      </el-table-column>
      <el-table-column label="作者" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.author ? scope.row.author.fullName : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="简介" width="300" align="center">
        <template slot-scope="scope">
          {{ scope.row.summary }}
        </template>
      </el-table-column>
      <el-table-column label="权重" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.weight }}
        </template>
      </el-table-column>
      <el-table-column label="总访问量" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.statData ? scope.row.statData.pvTotal : 0 }}
        </template>
      </el-table-column>
      <el-table-column label="总评论量" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.statData ? scope.row.statData.cmtCount : 0 }}
        </template>
      </el-table-column>
      <el-table-column label="总点赞量" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.statData ? scope.row.statData.agreeCount : 0 }}
        </template>
      </el-table-column>
      <el-table-column label="分享赞量" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.statData ? scope.row.statData.shareCount : 0 }}
        </template>
      </el-table-column>
      <el-table-column label="审核状态" width="160" align="center">
        <template slot-scope="scope">
          {{ auditStatus[scope.row.auditStatus] }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="发布时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.createdAt }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="更新时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>    {{ scope.row.updatedAt }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="文章状态" width="160">
        <template slot-scope="scope">
          <span>{{ scope.row.onShelve ? '上架' : '下架' }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="240">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row.id)">详情</el-button>
          <el-button v-if="scope.row.auditStatus === 'Publish'" size="mini" :type="scope.row.onShelve ? 'danger' : 'primary'" @click="handleStaus(scope.row)">{{ scope.row.onShelve ? '下架' : '上架' }}</el-button>
          <el-button size="mini" type="danger" @click="handleDel(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="page_count"
      background
      hide-on-single-page
      :page-sizes="[10, 20, 50, 100]"
      :page-size="10"
      layout="total, prev, pager, next, jumper, sizes"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { getArtList, delArt, changeStatus } from '@/api/art'
import { getVideoList, delVideo, changeVideoStatus } from '@/api/video'
import ResizeSiteorBiz from '../../mixins/ResizeSiteorBiz'

export default {
  mixins: [ResizeSiteorBiz],
  data() {
    return {
      list: [],
      listLoading: true,
      loading: false,
      form: {
        auditStatus: '',
        author: '',
        createAt: [],
        createBy: '',
        ids: '',
        isTagged: '',
        keyord: '',
        name: '',
        publishAt: [],
        referIds: '',
        tag: '',
        updateAt: [],
        tagAt: []
      },
      asyncFn: {},
      total: 0,
      totalPage: null,
      queryData: {
        pageSize: 10,
        pageNum: 1
      },
      auditStatus: { Pending: '待审', Auditing: '审核中', Publish: '通过', Deleted: '删除' }
    }
  },
  created() {
    console.log('路由信息', this.$route)
    this.type = this.$route.name === 'ArtContent' ? 'articles' : 'video'
    if (this.type === 'video') {
      this.asyncFn.asyncGetList = getVideoList
      this.asyncFn.asyncDel = delVideo
      this.asyncFn.asyncHandle = changeVideoStatus
    } else {
      this.asyncFn.asyncGetList = getArtList
      this.asyncFn.asyncDel = delArt
      this.asyncFn.asyncHandle = changeStatus
    }
    this.fetchData(this.queryData)
  },
  methods: {
    fetchData(data) {
      if (this.totalPage !== null && this.queryData.pageNum > this.total) return
      this.listLoading = true
      this.asyncFn.asyncGetList(data).then(res => {
        this.list = res.content
        this.listLoading = false
        this.totalPage = res.totalPage
        this.total = res.total
        this.queryData.pageNum += 1
      })
    },
    onSubmit() {
      const formData = JSON.parse(JSON.stringify(this.form))
      if (formData.createAt.length) {
        formData.minCreateAt = formData.createAt[0]
        formData.maxCreateAt = formData.createAt[1]
      }
      if (formData.updateAt.length) {
        formData.minUpdateAt = formData.updateAt[0]
        formData.maxUpdateAt = formData.updateAt[1]
      }
      if (formData.publishAt.length) {
        formData.minPublishAt = formData.publishAt[0]
        formData.maxPublishAt = formData.publishAt[1]
      }
      if (formData.tagAt.length) {
        formData.minTaggedAt = formData.tagAt[0]
        formData.maxTaggedAt = formData.tagAt[1]
      }
      delete formData.createAt
      delete formData.updateAt
      delete formData.tagAt
      delete formData.publishAt
      formData.pageNum = 1
      this.queryData = Object.assign(this.queryData, formData)
      Object.keys(this.queryData).forEach(item => {
        if (!this.queryData[item]) {
          delete this.queryData[item]
        }
      })
      // this.totalPage !== null && this.queryData.pageNum > this.total
      this.totalPage = null
      this.total = null
      this.fetchData(this.queryData)
    },
    handleSizeChange(val) {
      this.totalPage = null
      this.queryData.pageSize = val
      this.queryData.pageNum = 1
      this.fetchData(this.queryData)
    },
    handleCurrentChange(val) {
      this.queryData.pageNum = val
      this.fetchData(this.queryData)
    },
    handleEdit(id) {
      switch (this.type) {
        case 'video':
          this.$router.push(`/content/videoDetail/${id}`)
          break
        case 'articles':
          this.$router.push(`/content/artDetail/${id}`)
          break
        default:
          break
      }
    },
    handleDel(id) {
      if (this.loading) {
        this.$message.warning({
          message: '操作过于频繁，请稍后再试'
        })
        return
      }
      this.$confirm(`是否删除该${this.type === 'video' ? '视频' : '文章'}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        const loading = this.$loading({
          text: '提交中...'
        })
        this.loading = true
        this.asyncFn.asyncDel(id).then(res => {
          if (!res) {
            this.$message.success({
              message: '删除成功'
            })
            this.resetData()
          } else {
            throw new Error('删除失败')
          }
        }).catch(err => {
          console.log('删除错误', err)
          this.$message.error({
            message: '删除失败'
          })
        }).finally(() => {
          this.loading = false
          loading.close()
        })
      }).catch(() => {})
    },
    handleStaus(item) {
      if (this.loading) {
        this.$message.warning({
          message: '操作过于频繁，请稍后再试'
        })
        return
      }
      const loading = this.$loading({
        text: '提交中...'
      })
      this.loading = true
      // onShelve

      this.asyncFn.asyncHandle(item.id, !item.onShelve).then(res => {
        if (res.id) {
          this.$message.success({
            message: '操作成功'
          })
          item.onShelve = !item.onShelve
          // this.resetData()
        } else {
          throw new Error('操作失败')
        }
      }).catch(err => {
        console.log('操作错误', err)
        this.$message.error({
          message: '操作失败'
        })
      }).finally(() => {
        this.loading = false
        loading.close()
      })
    },
    resetData() {
      this.$refs.form.resetFields()
      this.totalPage = null
      this.total = 0
      this.queryData = {
        pageSize: 10,
        pageNum: 1
      }
      this.fetchData(this.queryData)
    }

  }
}
</script>
<style lang="scss" scoped>
 .app-container{
   overflow: hidden;
   padding-bottom: 30px;
   ::v-deep thead{
     color:#606266;
   }
     .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  ::v-deep .el-table .cell{
    line-height: normal;
  }
  .page_count{
    margin-top: 30px;
    float: right;
  }
  ::v-deep .el-pagination__sizes{
    margin-left: 20px;
  }
 }
</style>
